package myLearnjdk.guava;

import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.checkerframework.checker.nullness.qual.Nullable;

import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;

/**
 * guava并发学习
 * @author BriansPC
 *
 */
public class Concurrent {
	
	public static void main(String[] args) {
		listenableFuture();
		
	}
	
	
	/**
	 * ListenableFuture继承了jdk并发包下面得Future接口
	 */
	public static void listenableFuture(){
		/**
		 * 通过包装Executors来创建guava得ListeningExecutorService
		 * 
		 * ListeningExecutorService类似于jdk中得ExecutorService
		 */
		ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(3));
		ListenableFuture<Object>  myFutrue = service.submit(new Callable<Object>() {

			/**
			 * call()方法除了可以返回值之外，还可以抛出一个异常！！！！
			 */
			
			@Override
			public Object call() throws Exception {
				int i=3;
				while(i>0){
					System.out.println("执行一次......");
					i--;
					Thread.sleep(1000);
				}
//				return null;
				throw new RuntimeException(" 线程抛出异常");
			}
		});
		/**
		 * 给myFutrue添加回调方法（这是jdk得future所不支持得）
		 */
		Futures.addCallback(myFutrue, new FutureCallback<Object>() {

			@Override
			public void onSuccess(@Nullable Object result) {
				// TODO Auto-generated method stub
				
				System.out.println("执行成功");
			}

			@Override
			public void onFailure(Throwable t) {
				// TODO Auto-generated method stub
				
				System.err.println("执行失败："+t.getMessage());
			}
		},Executors.newFixedThreadPool(1));
	}
	
}
